package tech.veedo.munchkin.verifications.backend.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tech.veedo.munchkin.beans.backend.Node;
import tech.veedo.munchkin.constants.Operation;
import tech.veedo.munchkin.verifications.backend.NodeVerify;

@Slf4j
@Service
public class NodeVerifyImpl implements NodeVerify {

    @Override
    public boolean verify(Operation operation, Node node) {
        switch (operation) {
            case ADD:
                return addVerify(node);
            case UPDATE:
                return updateVerify(node);
            default:
                return true;
        }
    }

    private boolean addVerify(Node node) {
        nameNotNull(node.getName());
        mappingIDNotNull(node.getMappingID());
        sortNotNull(node.getSort());
        sortMustGreatThen0(node.getSort());
        return true;
    }

    private boolean updateVerify(Node node) {
        idNotNull(node.getId());
        sortMustGreatThen0(node.getSort());
        return true;
    }

    private void idNotNull(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("审核节点ID为空");
        }
    }

    private void nameNotNull(String name) {
        if (StringUtils.isEmpty(name)) {
            throw new NullPointerException("审核节点名称为空");
        }
    }

    private void mappingIDNotNull(Long mappingID) {
        if (ObjectUtils.isEmpty(mappingID)) {
            throw new NullPointerException("审核节点mappingID为空");
        }
    }

    private void sortNotNull(Integer sort) {
        if (ObjectUtils.isEmpty(sort)) {
            throw new NullPointerException("审核节点sort为空");
        }
    }

    private void sortMustGreatThen0(Integer sort) {
        if (!ObjectUtils.isEmpty(sort) && sort < 1) {
            throw new IllegalArgumentException("审核节点的顺序的值要大于等于1");
        }
    }

}
